﻿using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using XRM.Security.WebUI.Enums;
using XRM.Security.WebUI.Helpers;
using XRM.Security.WebUI.Models.Account;
using XRM.Security.WebUI.Security;

namespace XRM.Security.WebUI.Controllers
{
    public class AccountController : BaseController
    {
        public const string ErrorMessageCookieName = "AccessErrorMessage";
        public const int UserNotRegistredErrorCode = 401;

        [HttpGet]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            AddErrorMessageFromCookie();
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if ( ActiveDirectoryService.Validate( model.UserName, model.Password ) )
                {
                    var systemUser = SystemUserRepository.GetByLogin( model.UserName );
                    if ( systemUser != null )
                    {
                        if (!RoleMemberRepository.GetAll(x => x.UserId == systemUser.Id).Any())
                        {
                            ShowAlert(AlertType.Error, "Нет прав на работу в системе. Обратитесь к администратору системы.");
                            return View(model);
                        }

                        FormsAuthentication.SetAuthCookie( model.UserName, model.RememberMe );
                        return RedirectToLocal( returnUrl );
                    }
                }
            }

            ShowAlert(AlertType.Error, "Неправильный логин или пароль.");
            return View(model);
        }
        
        [HttpGet]
        public ActionResult LogOff()
        {
            if ( UserPrincipal != null )
            {
                new CurrentUserService().DeletePrincipal( HttpContext );
                FormsAuthentication.SignOut();
            }
            return RedirectToAction("Login");
        }
 
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        private void AddErrorMessageFromCookie()
        {
            var error = this.GetCookie( ErrorMessageCookieName );
            if (error != null)
            {
                ShowAlert(AlertType.Error, "Пользователь не зарегистрирован.");
                this.RemoveCookie( ErrorMessageCookieName, "/" );
            }
        }
    }
}
